<%@page import="entity.Admin"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
Admin admin = (Admin) session.getAttribute("admin");
%>

<div class="callout callout-left">
  <span class="callout-title text-muted">部门：<%=admin.getDeptName() %></span><!-- &nbsp;<span class="glyphicon glyphicon-question-sign"></span> -->
  <a class="btn btn-primary" data-toggle="modal" href="#myModal" id="create_admin" style="margin-left: 35px;"><span class="glyphicon glyphicon-plus-sign">&nbsp;新建管理员</span></a>
</div>

<div class="callout">
  <form class="form-inline" onsubmit="return false;">
  <div class="form-group">
    <label for="adminName_search">账号：</label>
    <input type="text" class="form-control" id="adminName_search"  name="adminName_search" placeholder="管理员账号" autocomplete="off" />
  </div>
  <div class="form-group">
    <label for="deptName_search">所属部门：</label>
    <select class="form-control" id="deptName_search" name="deptName_search" >
    	<option value="">--请选择--</option>
    </select>
  </div>
  <div class="form-group">
    <label for="priv_search">包含权限：</label>
    <input class="form-control" type="text" list="privs_list" id="priv_search" name="priv_search" placeholder="单权限查询" />
	<datalist id="privs_list"></datalist>
  </div>
  <div class="form-group">
    <label for="status_search">状态：</label>
    <select class="form-control" id="status_search"  name="status_search">
      <option value="">--请选择--</option>
      <option value="正常">正常</option>
      <option value="禁用">禁用</option>
    </select>
  </div>&nbsp;&nbsp;&nbsp;
  <div class="form-group">
    <a class="btn btn-primary" id="doSearch" href="javascript:;"><span class="glyphicon glyphicon-search">&nbsp;搜索</span></a>&nbsp;&nbsp;&nbsp;
  </div>
  <!-- <a class="btn btn-info" id="cleansearch" href="javascript:;"><span class="glyphicon glyphicon-remove-circle">&nbsp;清除</span></a> -->
</form>
</div>

<div class="callout callout-white">
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
        <tr>
          <th>编号</th>
          <th>账号</th>
          <th>所属部门</th>
          <th>管理员类别</th>
          <th>权限</th>
          <th>审批用户数量</th>
          <th>创建时间</th>
          <th>状态</th>
          <th>动作</th>
        </tr>
      </thead>
      <tbody id="admins_content">
      </tbody>
    </table>
  </div>
</div>

<script>
require.config({
	baseUrl: '<%=path %>/js',
	paths: {
		jquery: 'jquery-1.9.1.min',
		commmon: 'common',
		bootstrapswitch: 'bootstrap-switch.min',
		md5: 'md5'
	}
});

require(['jquery', 'common', 'md5', 'bootstrapswitch'], function($, common, md5) {
//console.log("管理员管理模块载入");

var workspace = function() {

	var domKey;
	var dataOpt;
	
	var admins;	
	var departments;	
	var privNames;
	
  var privsEdit = {
		addPrvis: "",// 新增权限
		delPrivs: "",// 删除权限
		oldPrivs: "",// 旧权限
		newPrivs: ""// 新权限
	}

	var init = function() {
		domKey = common.commData.domKey;
		dataOpt = common.dataOpt;

		departments = common.ajaxLoadData(dataOpt.departmentOpt);
		privNames = common.ajaxLoadData(dataOpt.privNameOpt);

		_initAdminsTable();// ->编辑、->删除操作
		_createAdmin();// ->创建操作
		_searchInit();
	}

	// 全选/不全选
	var checkedChange = function(ids) {
		for(var i = 0, n = ids.length; i < n; i++) {
			common.checkedChange(ids[i]);
		}
	}

	// 状态切换按钮
	var initSwitch = function() {
		$(".bootstrap-switch").each(function() {
			var f;
			var $st = $(this).parent().find("[name='status_text']");
			$(this).find(":input:checkbox").bootstrapSwitch({
				animate: true,
				handleWidth: "5px",
				onText: "&nbsp;&nbsp;&nbsp;&nbsp;",
				offText: "&nbsp;&nbsp;&nbsp;&nbsp;",
				onInit: function() {// 按钮初始化动作
          if("正常" === $st.html()) {
            $st.removeClass("text-danger").addClass("text-success");
            f = true;
          } else {
            $st.removeClass("text-success").addClass("text-danger");
            f = false;
          }
				},
				onSwitchChange: function(e, state) {
					var name = $(this).data("name");
					if(true == state) {// 启用
						$st.removeClass("text-danger").addClass("text-success").html("正常");
						common.switchStatusAjax("admins", "正常", name);
					} else {// 禁用
						$st.removeClass("text-success").addClass("text-danger").html("禁用");
						common.switchStatusAjax("admins", "禁用", name);
					}
				}
			});
			$(this).find(":checkbox").bootstrapSwitch('state', f);
		});
	}

	// 部门管理员限制的四个个权限
	var deptPrivLimit = function() {
		$("#isSuper").change(function() {
			if($(this).val() == "部门") {
				$("#basic-priv-admin").attr({"disabled":true,"checked":false});
				$("#basic-priv-dept").attr({"disabled":true,"checked":false});
        $("#active-priv-soft").attr({"disabled":true,"checked":false});
        $("#active-priv-dept-assign").attr({"disabled":true,"checked":false});
			} else {
				$("#basic-priv-admin").attr({"disabled":false});
				$("#basic-priv-dept").attr({"disabled":false});
        $("#active-priv-soft").attr({"disabled":false});
        $("#active-priv-dept-assign").attr({"disabled":false});
			}
		}).change();
		
		$("#basic-priv-admin").change(function(){$("#isSuper").change();});
		$("#basic-priv-dept").change(function(){$("#isSuper").change();});
    $("#active-priv-soft").change(function(){$("#isSuper").change();});
    $("#active-priv-dept-assign").change(function(){$("#isSuper").change();});
	}

	// 分页功能
	var pageNav = function(htmlArr) {
		var opt = {
			htmlArr: htmlArr,
			content: $("#admins_content"),
		}
		common.pageNav(opt, function() {
      initSwitch();
      editAdmin();
      delAdmin();
    });
	}

	// 管理员列表
	var _initAdminsTable = function() {
		admins = common.ajaxLoadData(dataOpt.adminOpt);
		dataOpt.adminOpt.data = {}

		var template = "<tr><th scope='row'>#row#</th>" +
      "<td>#adminName#</td>" +
      "<td>#deptName#</td>" +
      "<td>#isSuper#</td>" +
      "<td style='max-width:450px;white-space:normal;'>#privs#</td>" +
      "<td>#approveNum#</td>" +
      "<td>#createDate#</td>" +
      "<td>" +
      "<div class='bootstrap-switch bootstrap-switch-mini' style='top: -1px;'><input type='checkbox' checked data-name='#adminName#' /></div>" +
      "&nbsp;<span name='status_text'>#status#</span>" +
      "</td>" +
      "<td>" +
      "<a href='#myModal' class='editAdmin' data-toggle='modal' data-name='#adminName#'><span class='glyphicon glyphicon-edit text-primary'>编辑</span></a>&nbsp;&nbsp;" +
      "<a href='#myModal' class='delAdmin' data-toggle='modal' data-name='#adminName#'><span class='glyphicon glyphicon-remove text-primary'>删除</span><a>" +
      "</td></tr>";

    var row = 0;
    var htmlArr = [];
    var html = "";
    var thisT = "";
    for(var i = 0, n = admins.length; i < n; i++ ) {
      if("超级" !== admins[i]["isSuper"]) {// 不显示超级管理员
        thisT = template;
        thisT = thisT.replace(/#row#/g, ++row).replace(/#adminName#/g, admins[i]["adminName"]).replace(/#privs#/g, admins[i]["privs"])
          .replace(/#deptName#/g, admins[i]["deptName"]).replace(/#status#/g, admins[i]["status"]).replace(/#isSuper#/g, admins[i]["isSuper"] + "管理员")
          .replace(/#createDate#/g, admins[i]["createDate"]).replace(/#approveNum#/, admins[i]["approveNum"]);
        html += thisT;
        if((row !== 0) && (row % common.commData.pageNum === 0)) {
          htmlArr.push(html);
          html = "";
        }
      }
    }

    if("" !== html) {
      htmlArr.push(html);// 插入不满pageNum的几条数据
    }

    pageNav(htmlArr);
	}

	// 创建管理员
	var _createAdmin = function() {
		var modalBodyTemplate = "<form class='form-horizontal'>" +
      "<div class='form-group'>" +
      "<label for='deptName' class='col-sm-3 control-label'>所属部门</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' id='deptName' name='deptName'>" +
      "</select></div></div>" +
      "<div class='form-group'>" +
      "<label for='adminName' class='col-sm-3 control-label'>账号</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' name='adminName' id='adminName' placeholder='管理员登陆账号' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='password' class='col-sm-3 control-label'>密码</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' name='password' id='password' class='form-control' placeholder='管理员登陆密码' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='isSuper' class='col-sm-3 control-label'>管理员类别</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' id='isSuper' name='isSuper'>" +
      "</select></div></div>" +
      "<div class='form-group'>" +
      "<label for='cnName' class='col-sm-3 control-label'>真实姓名</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' name='cnName' id='cnName' placeholder='真实姓名' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='phone' class='col-sm-3 control-label'>电话</label>" +
      "<div class='col-sm-9'>" +
      "<input type='tel' class='form-control' name='phone' id='phone' placeholder='联系电话' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='email' class='col-sm-3 control-label'>邮箱</label>" +
      "<div class='col-sm-9'>" +
      "<input type='email' class='form-control' name='email' id='email' placeholder='请输入正确的邮箱地址' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label class='col-sm-3 control-label'>权限</label>" +
      "<div class='col-sm-9'>" +
      "<fieldset><legend><label class='checkbox-inline'><input type='checkbox' id='basic' /><b>基础管理</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-admin' value='管理员管理'/>管理员管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-dept' value='部门管理'/>部门管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-app' value='应用管理'/>应用管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-user' value='用户管理'/>用户管理</label>" +
      "</fieldset><fieldset>" +
      "<legend><label class='checkbox-inline'><input type='checkbox' id='active'/><b>激活管理</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-soft' value='软件管理'/>软件管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-user-active' value='用户激活情况'/>用户激活情况</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-user-approve' value='用户许可审批'/>用户许可审批</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-dept-assign' value='部门许可分配'/>部门许可分配</label>" +
      "</fieldset><fieldset>" +
      "<legend><label class='checkbox-inline'><input type='checkbox' id='chart'/><b>数据统计</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-key' value='密钥数量统计'/>密钥数量统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-signup' value='注册用户统计'/>注册用户统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-assign' value='软件许可统计'/>软件许可统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-err' value='激活错误统计'/>激活错误统计</label>" +
      "</fieldset></div></div>" +
      "<div class='form-group'>" +
      "<label for='status' class='col-sm-3 control-label'>状态</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' id='status'>" +
      "<option value='正常'>正常</option>" +
      "<option value='禁用'>禁用</option>" +
      "</select></div></div></form>";

    $("#create_admin").click(function() {
      common.cleanModal();
      domKey.modalLabel.html("新建管理员");
      domKey.modalBody.html(modalBodyTemplate);

      // 部门数据填充
			for(var i = 0, n = departments.length; i < n; i++) {
				var opt = document.createElement("option");
				$(opt).val(departments[i]["deptName"]);
				$(opt).text(departments[i]["deptName"]);
        $("#deptName").append(opt);
      }

			// 管理员类别选项控制
      if("超级" === "<%=admin.getIsSuper() %>") {
        var thisT = "<option value='校级'>校级管理员</option><option value='部门'>部门管理员</option>";
        $("#isSuper").html(thisT);
      } else if ("校级" == "<%=admin.getIsSuper() %>") {
        var thisT = "<option value='部门'>部门管理员</option>";
        $("#isSuper").html(thisT);
      }

      checkedChange(["basic", "active", "chart" ]);// 全选不全选绑定
      deptPrivLimit();// 部门管理员不拥有的4个基础管理

      domKey.modalAct.html("新建")
			.on("click", function() {
				common.disable(domKey.modalAct);// 提交请求则禁掉按钮
				// 得到所选权限
				var privs = "";
				domKey.modalBody.find(":checkbox[id*='-priv-']:checked").each(function() {
					privs += ($(this).val() + "、");
				});
				if("、" === privs.charAt(privs.length - 1)) {
					privs = privs.substring(0, privs.length - 1);
				}
				// 获取填写的数据
				var data = {
          "adminName": $("#adminName").val(),
          "deptName": $("#deptName option:selected").val(),
          "password": md5($("#password").val()), // $("#password").val(),
          "cnName": $("#cnName").val(),
          "email": $("#email").val(),
          "isSuper": $("#isSuper option:selected").val(),
          "status": $("#status option:selected").val(),
          "phone": $("#phone").val(),
          "privs": privs
				}

				if(data["adminName"].length === 0 || data["password"].length === 0 || data["cnName"].length === 0 ||
					data["email"].length === 0 || data["phone"].length === 0) {
					swal("请填写所有信息","", "warning")
					common.enable(domKey.modalAct);
				} else if(!common.isName(data["adminName"])) {
          swal("提示", "用户名只能包含字母、数字和下划线的字符", "warning");
          common.enable(domKey.modalAct);
        }else if(!common.isPasswd($("#password").val())) {
          swal("提示", "密码只能6-20个包含字母、数字和下划线的字符", "warning");
          common.enable(domKey.modalAct);
				} else {
					$.ajax({
						url: "<%=path %>/servlet/admin/CreateAdminServlet",
						type: "post",
						data: data,
						dataType: "json",
						async: false,
						success: function(json) {
							if("1" == json["retCode"]) {

							} else {
								alert(json["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("CreateAdminServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initAdminsTable();// 刷新表格
						}
					});
				}
			});
    });
	}
	
	// 编辑管理员
	var editAdmin = function() {
		var modalBodyTemplate = "<form class='form-horizontal'>" +
			"<div class='form-group'>" +
      "<label for='adminName' class='col-sm-3 control-label'>账号</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' name='adminName' id='adminName' placeholder='管理员登陆账号' readonly/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='deptName' class='col-sm-3 control-label'>所属部门</label>" +
      "<div class='col-sm-9'>" +
      "<select class='form-control' id='deptName' name='deptName'>" +
      "</select></div></div>" +
      "<div class='form-group'>" +
      "<label for='password' class='col-sm-3 control-label'>密码</label>" +
      "<div class='col-sm-9'>" +
      "<label class='checkbox-inline'><input type='checkbox' id='password' name='password' />重置（初始密码：123qwe）</label>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='isSuper' class='col-sm-3 control-label'>管理员类别</label>" +
      "<div class='col-sm-9'>" +
      "<div id='super_type'></div>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='cnName' class='col-sm-3 control-label'>真实姓名</label>" +
      "<div class='col-sm-9'>" +
      "<input type='text' class='form-control' name='cnName' id='cnName' placeholder='真实姓名' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='phone' class='col-sm-3 control-label'>电话</label>" +
      "<div class='col-sm-9'>" +
      "<input type='tel' class='form-control' name='phone' id='phone' placeholder='联系电话' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='email' class='col-sm-3 control-label'>邮箱</label>" +
      "<div class='col-sm-9'>" +
      "<input type='email' class='form-control' name='email' id='email' placeholder='请输入正确的邮箱地址' autocomplete='off' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label class='col-sm-3 control-label'>权限</label>" +
      "<div class='col-sm-9'>" +
      "<fieldset><legend><label class='checkbox-inline'><input type='checkbox' id='basic' /><b>基础管理</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-admin' value='管理员管理'/>管理员管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-dept' value='部门管理'/>部门管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-app' value='应用管理'/>应用管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='basic-priv-user' value='用户管理'/>用户管理</label>" +
      "</fieldset><fieldset>" +
      "<legend><label class='checkbox-inline'><input type='checkbox' id='active'/><b>激活管理</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-key' value='密钥管理'/>密钥管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-soft' value='软件管理'/>软件管理</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-user-active' value='用户激活情况'/>用户激活情况</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-user-approve' value='用户许可审批'/>用户许可审批</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='active-priv-dept-assign' value='部门许可分配'/>部门许可分配</label>" +
      "</fieldset><fieldset>" +
      "<legend><label class='checkbox-inline'><input type='checkbox' id='chart'/><b>数据统计</b></label></legend>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-key' value='密钥数量统计'/>密钥数量统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-signup' value='注册用户统计'/>注册用户统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-assign' value='软件许可统计'/>软件许可统计</label>" +
      "<label class='checkbox-inline'><input type='checkbox' id='chart-priv-err' value='激活错误统计'/>激活错误统计</label>" +
      "</fieldset></div></div><input type='hidden' id='password_hide' value=''/></form>";

		$(".editAdmin").each(function() {
			$(this).click(function() {
        common.cleanModal();
        domKey.modalLabel.html("修改管理员");
        domKey.modalBody.html(modalBodyTemplate);
	      		
        // 部门数据填充
				for(var i = 0, n = departments.length; i < n; i++) {
					var opt = document.createElement("option");
					$(opt).val(departments[i]["deptName"]);
					$(opt).text(departments[i]["deptName"]);
            $("#deptName").append(opt);
        }

        // 管理员三字补充
        var isT  = "";

        // 权限控制
        if("超级" == "<%=admin.getIsSuper() %>") {
          var thisT = "<select class='form-control' id='isSuper' name='isSuper'>" +
            "<option value='校级'>校级管理员</option><option value='部门'>部门管理员</option>" +
            "</select>";
          $("#super_type").html(thisT);
        } else if ("校级" == "<%=admin.getIsSuper() %>"){
          isT = "管理员";
          var thisT = "<input type='text' class='form-control' id='isSuper' name='isSuper' value='' readonly />";
          $("#super_type").html(thisT);
        }

        backfillData($(this).data("name"), isT);// 回填修改模态框数据并的到旧权限
        checkedChange(["basic", "active", "chart" ]);// 全选不全选绑定
        deptPrivLimit();

        domKey.modalAct.html("保存")
				.on("click", function() {
					common.disable(domKey.modalAct);// 提交请求则禁掉按钮
					privsEdit.newPrivs = "";
					domKey.modalBody.find(":checkbox[id*='-priv-']:checked").each(function() {
						privsEdit.newPrivs += ($(this).val() + "、");
					});
					if("、" == privsEdit.newPrivs.charAt(privsEdit.newPrivs.length - 1)) {
						privsEdit.newPrivs = privsEdit.newPrivs.substring(0, privsEdit.newPrivs.length - 1);// 得到新的权限
					}
					classifyPrivs();// 区别出新增和删除的权限
//					console.log("old: " + privsEdit.oldPrivs);
//					console.log("new: " + privsEdit.newPrivs);
//					console.log("add: " + privsEdit.addPrivs);
//					console.log("del: " + privsEdit.delPrivs);

					// 获取填写的数据
					var data = {
						"adminName": $("#adminName").val(),
						"deptName": $("#deptName option:selected").val(),
						"password": $("#password").is(":checked") ? md5("123qwe") : $("#password_hide").val(),
						"cnName": $("#cnName").val(),
						"email": $("#email").val(),
						"isSuper": $("#isSuper option:selected").val(),
						"phone": $("#phone").val(),
						"addPrivs": privsEdit.addPrivs,
						"delPrivs": privsEdit.delPrivs
					}

					if(data["cnName"].length === 0 || data["email"].length === 0 || data["phone"].length === 0) {
						swal("请填写所有信息", "", "warning");
						common.enable(domKey.modalAct);
					} else {
						$.ajax({
							url: "<%=path %>/servlet/admin/EditAdminServlet",
							type: "post",
							data: data,
							dataType: "json",
							async: false,
							success: function(json) {
								if("1" == json["retCode"]) {

								} else {
									alert(json["desc"]);
								}
							},
							error: function(XMLHttpRequest, textStatus, errorThrown) {
								alert("EditAdminServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
							},
							complete: function() {
								domKey.modal.find(".close").click();
								_initAdminsTable();// 刷新表格
							}
						});
					}
				});
      });
		});

		// 修改功能数据回显
		var backfillData = function(adname, isT) {
			for(var i = 0, n = admins.length; i < n; i++) {
				if(admins[i]["adminName"] == adname) {
					$("#adminName").val(admins[i]["adminName"]);
					$("#deptName").val(admins[i]["deptName"]);
					$("#password_hide").val(admins[i]["password"]);
					$("#cnName").val(admins[i]["cnName"]);
					$("#email").val(admins[i]["email"]);
					$("#isSuper").val(admins[i]["isSuper"] + isT);
					// $("#status").val(admins[i]["status"]);
					$("#phone").val(admins[i]["phone"]);
					showPrivs(admins[i]["privs"]);
					privsEdit.oldPrivs = "";
					privsEdit.oldPrivs = admins[i]["privs"];// 得到旧的权限
					break;
				}
			}
		}
		var showPrivs = function(privs) {
			var privArr = [];
			privArr = privs.split("、");
			$(":checkbox[id*='-priv-']").each(function() {
				for(var i = 0; i < privArr.length; i++) {
					if($(this).val() === privArr[i]) {
						$(this).prop("checked", true);
						privArr.splice(i, 0);// 减少压力
					}
				}
			});
		}

		// 找出新增、删除的权限
		var classifyPrivs = function() {
			privsEdit.delPrivs = "";
			privsEdit.addPrivs = "";
			privsEdit.delPrivs = setPrivs(privsEdit.oldPrivs.split("、"), privsEdit.newPrivs.split("、"));
			privsEdit.addPrivs = setPrivs(privsEdit.newPrivs.split("、"), privsEdit.oldPrivs.split("、"));
		}
		var setPrivs = function(front, after) {
			var p = "";
			var f;
			for(var i = 0, n = front.length; i < n; i++) {
				f = true;
				for(var j = 0, m = after.length; j < m; j++) {
					if(front[i] == after[j]) {
						f = false;
						after.splice(j, 1);
						break;
					}
					f = true;
				}
				if(f) {
					p += front[i] + "、";
				}
				
			}
			return p.substring(0, p.length - 1);
		}
	}

	// 删除管理员
	var delAdmin = function() {
		var modalBodyTemplate = "<span class='glyphicon glyphicon-info-sign' style='color:#FF8A00;font-size:26px;margin-right:15px;top:7px;'></span>确认删除#name#？";
		$(".delAdmin").each(function() {
			var adminName = $(this).data("name");
			$(this).on("click", function() {
				common.cleanModal();
				domKey.modal.find(".modal-dialog").addClass("modal-sm");
				var thisTemplate = modalBodyTemplate;
				thisTemplate = thisTemplate.replace(/#name#/g, adminName);
				domKey.modalLabel.html("删除管理员");
				domKey.modalBody.html(thisTemplate);
				
				domKey.modalAct.html("确认")
				.on("click", function() {
					common.disable(domKey.modalAct);// 提交请求则禁掉按钮
					$.ajax({
						url: "<%=path %>/servlet/admin/DelAdminServlet",
						type: "post",
						data: {"adminName": adminName},
						dataType: "json",
						async: false,
						success: function(json) {
							if("1" == json["retCode"]) {

							} else {
								alert(json["desc"]);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							alert("DelAdminServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState+ ":" + textStatus);
						},
						complete: function() {
							domKey.modal.find(".close").click();
							_initAdminsTable();// 刷新表格
						}
					});
				});
			});
		});
	}
	
	// 查询功能
	var _searchInit = function() {
		// 部门数据
		for(var i = 0, n = departments.length; i < n; i++) {
			var op = document.createElement("option");
			$(op).val(departments[i]["deptName"]);
			$(op).text(departments[i]["deptName"]);
			$("#deptName_search").append(op);
		}
		
		// 权限数据
		for(var i = 0, n = privNames.length; i < n; i++) {
			var op = document.createElement("option");
			$(op).val(privNames[i]);
			$(op).text(privNames[i]);
			$("#privs_list").append(op);
		}
		
		$("#doSearch").click(function() {
			// 数据初始化
			common.commData.curPage = 0;

			// 搜索条件
			dataOpt.adminOpt.data = {
				"adminName": $("#adminName_search").val(),
				"deptName": encodeURI(encodeURI($("#deptName_search").val())),
				"priv": encodeURI(encodeURI($("#priv_search").val())),// TODO：单权限查询
				"status": encodeURI(encodeURI($("#status_search").val()))
			}
			_initAdminsTable();
		});
	}
	
	return {
		init: init
	}
}();
	
$(function() { workspace.init(); });

});

requirejs.onError = function (err) {  
  console.error(err);
  if (err.requireType === 'timeout') {
    console.error('modules: ' + err.requireModules)
  }
  throw err;
}
</script>